<template>
    <Upload
        ref="upload"
        :action="url"
        :headers="headers"
        :format="format"
        :max-size="maxSize"
        :multiple="multiple"
        :default-file-list="defaultFileList"
        :before-upload="handleBeforeUpload"
        :on-format-error="handleFormatError"
        :on-success="handleSuccess"
        :on-error="handleError"
    >
        <Button icon="ios-cloud-upload-outline">上传文件</Button>
    </Upload>
</template>

<script>
import Cookies from 'js-cookie';
import { host } from '@/config/index.js';
export default {
    name: 'BaseUpload',
    props: {
        format: {
            type: Array,
            default: function() {
                return ['txt', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'rar', 'zip', '7z', 'gz', 'pdf', 'wps', 'md'];
            }
        },
        multiple: { // 是否支持多选
            type: Boolean,
            default: false
        },
        maxSize: { // 图片大小限制，KB为单位
            type: Number,
            default: 2048
        },
        limit: { // 上传数量限制
            type: Number,
            default: 5
        },
        defaultFileList: {
            type: Array,
            default: function() {
                return [];
            }
        }
    },
    data() {
        return {
            url: host + '/attachmentApi/upload',
            headers: {},
            uploadList: []
        }
    },
    mounted() {
        if(Cookies.get('token')) {
            this.headers.Authorization = 'Bearer ' + Cookies.get('token');
        }
        this.uploadList = this.$refs.upload.fileList;
    },
    methods: {
        handleFormatError (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: file.name + ' 的格式不正确， 请选择'+ this.format.join('、') +'格式的文件。'
            });
        },
        handleMaxSize (file) {
            // 单位换算
            let _Mb = this.maxSize / 1024;
            let f = _Mb.toString().split(".");
            if(f.length > 1) {
                _Mb = f[0] + '.' + f[1].substring(0, 2);
            }
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: file.name + ' 文件太大了， 请选择'+ _Mb +'M以内的文件。'
            });
        },
        handleBeforeUpload () {
            // 以下是校验上传数量限制
            const check = this.uploadList.length < this.limit;
            if (!check) {
                this.$Notice.warning({
                    title: '最多可以上传 '+ this.limit +' 个文件。'
                });
            }
            return check;
        },
        handleSuccess(response, file, fileList) {
            if(response.code !== 200) {
                this.$Message.error(response.message || '上传失败');
                const fileList = this.$refs.upload.fileList;
                this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
            }
        },
        handleError(error, file, fileList) {
            // console.log(error)
        },
        getFiles() {
            let files = this.$refs.upload.fileList.filter(item => {
                if(!item.response || item.response.code !== 200) return false;
                return true;
            });
            return files.map(item => {
                return item.response.data;
            });
        },
        // 提供清空上传列表的method，需要在父组件调用此method
        clearFiles() {
            this.$refs.upload.clearFiles();
        }
    }
}
</script>